package lucene.server.web.controller.admin;


import cn.hutool.db.Entity;
import cn.hutool.db.PageResult;
import lombok.extern.slf4j.Slf4j;
import lucene.server.common.utils.StringUtil;
import lucene.server.web.dao.SystemDao;
import lucene.server.web.model.LoginUser;
import lucene.server.common.model.Result;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.Map;


@RestController
@RequestMapping("/admin/user")
@Slf4j
public class UserController {

    @GetMapping(value = "/get")
    public Result<?> get(@RequestParam(name = "page",required = true,defaultValue = "0")int page, HttpServletRequest req) {
        PageResult<Entity> result = SystemDao.getPageAll("user", page,15,null);
        Map<String,Object> map = new HashMap<>();
        map.put("data",result);
        map.put("totalPage",result.getTotalPage());
        map.put("total",result.getTotal());
        map.put("page",result.getPage());
        return  Result.OK(map);
    }

    @PostMapping(value = "/update")
    public Result<?> updateConn(@RequestBody LoginUser user, HttpServletRequest req) {

        String error = checkUser(user);

        if (!StringUtil.isEmpty(error)){
            return Result.error(error);
        }
        SystemDao.insertOrUpdate(user);

        return Result.OK();
    }

    @PostMapping(value = "/delete")
    public Result<?> deleteConn(@RequestBody LoginUser user, HttpServletRequest req) {
        SystemDao.delete(user);
        return Result.OK();
    }
    private String checkUser(LoginUser user){
        String error = "";
        error += StringUtil.assertNull(user.getUsername(),"名称不能为空\n");
        error += StringUtil.assertNull(user.getPassword(),"密码不能为空\n");
        error += StringUtil.assertNull(user.getType(),"类型不能为空\n");
        return error;
    }
}

